// src/permission.js
import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import constantRouterMap from '@/router/router.config';

NProgress.configure({
  showSpinner: false,
});

const whiteList = ['/login'];

// 提取所有路由的路径
const extractRoutes = (routes, parentPath = '') => {
  return routes.reduce((acc, route) => {
    const currentPath = parentPath + (route.path.startsWith('/') ? route.path : '/' + route.path);
    // console.log('Current Path:', currentPath);

    if (route.children) {
      return acc.concat(currentPath, extractRoutes(route.children, currentPath));
    }
    return acc.concat(currentPath);
  }, []);
};

const allRoutes = extractRoutes(constantRouterMap);
console.log('All Routes:', allRoutes);

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  // console.log('To Path:', to.path, 'White List:', whiteList.includes(to.path), 'All Routes:', allRoutes.includes(to.path));

  if (whiteList.includes(to.path) || allRoutes.includes(to.path)) {
    next();
  } else {
    next({ path: '/login' }); // 重定向到登录页面
    NProgress.done();
  }
});

router.afterEach(() => {
  NProgress.done();
});